<?php namespace Admin\Controller; 
use Common\Model\GoodsList;
use Common\Model\GoodsAttr;

//GoodsList类控制器
class GoodsListController extends CommonController{
	//实例化Model中的GoodsList类
	private $model;
	public function __auto(){
		$this->model = new GoodsList;
	}
	
	//显示列表
	public function index(){		
		if(IS_POST){
			//调用模型文件里的Goods类的store方法
			if(!$this->model->store())	

				//提示错误
				View::error($this->model->getError());						
		}	
		/*显示字段*/
		//获取当前操作的商品
		$gid = $_SESSION['info']['gid'];
		/*添加数据*/
		//商品规格
		$goodsAttryData= Db::table('goods_attr ga')
			->join('type_attr ta','ga.type_attr_trid','=','ta.trid')
			->where("goods_gid={$gid} AND class=1")
			->orderBy('trid','ASC')
			->groupBy('trname')
			->get();
		//商品属性表
		$goodsAttrModel = new GoodsAttr;
		//添加货品的时候下拉菜单所选择的内容(一定是从商品属性表获得)
		foreach($goodsAttryData as $k=>$v){
			$goodsAttryData[$k]['value'] = $goodsAttrModel
			->where("type_attr_trid={$v['trid']} AND goods_gid={$gid}")->get();
		}		
		View::with('goodsAttryData',$goodsAttryData);
		
		/*显示旧数据*/
		$goodsLisgtData = $this->model->where('goods_gid',$gid)->orderBy('glid','ASC')->get();
		//把数据库中 combine 的id值换成商品属性表中 gvalue
		foreach($goodsLisgtData as $k=>$v){
			$goodsLisgtData[$k]['combine'] = $goodsAttrModel
			->where("gaid IN ({$v['combine']})")
			->orderBy('type_attr_trid','ASC')
			->get();			
		}
		View::with('goodsLisgtData',$goodsLisgtData);

		View::make();

	}

	//编辑
	public function edit(){
		/*2.执行添加*/
		if(IS_POST){
			//调用模型文件里的GoodsList类的store方法去执行数据添加
			if($this->model->edit()){
				//若模型类中数据验证正确，成功
				View::success('货物清单修改成功',U('GoodsList/index'));
			}
			//提示错误
			View::error($this->model->getError());
		}	
		/*1.获取旧数据*/		
		$glid = q('get.glid',null,'intval');
		//获取当前操作的商品
		$oldGoodsList = $this->model->where('glid',$glid)->find();
		//变成数组，便于循环
		$oldGoodsList['combine'] = explode(',', $oldGoodsList['combine']);
		View::with('oldGoodsList',$oldGoodsList);

		//获取商品gid
		$gid = $oldGoodsList['goods_gid'];
		//商品规格
		$goodsAttryData= Db::table('goods_attr ga')
			->join('type_attr ta','ga.type_attr_trid','=','ta.trid')
			->where("goods_gid={$gid} AND class=1")
			->orderBy('trid','ASC')
			->groupBy('trname')
			->get();
		//商品属性表
		$goodsAttrModel = new GoodsAttr;
		//添加货品的时候下拉菜单所选择的内容(一定是从商品属性表获得)
		foreach($goodsAttryData as $k=>$v){
			$goodsAttryData[$k]['value'] = $goodsAttrModel
			->where("type_attr_trid={$v['trid']} AND goods_gid={$gid}")->get();
		}		
		View::with('goodsAttryData',$goodsAttryData);		
		
	    View::make();
	}
	
	//删除
	public function del(){
		$glid = q('get.glid');
	    //执行删除
		$this->model->where("glid={$glid}")->delete();
		View::success('删除成功');
	}

}
